<template>
    <div class="common-layout">
        <el-row>
            <el-button @click="corr()">corr</el-button>
        </el-row>
        <el-row>
            <el-col :span="24">
            <el-table :data="state.data" height="700" style="width: 100%"
            @sort-change="sortChange"
            :default-sort="state.sort"
            :cell-class-name="tableCellClassName"
             >
                <el-table-column prop="etf" label="ETF" width="250" >
                    <template #default="scope">
                        <ToStockDetail :stock="scope.row.etf" />
                    </template> 
                </el-table-column>
                <el-table-column prop="rate" label="rate"  sortable/>
            </el-table>
            </el-col>
        </el-row>
    </div>
</template>

<script setup>
import ToStockDetail from './ToStockDetail.vue';
import { getLpClassName } from '../utils/help';
import { getStockEtfConstruct } from '../service/etf';
import { useRoute } from 'vue-router'
import { reactive, watch } from 'vue';
import { weekStockSearch } from '../stores/week'
import { storeToRefs } from 'pinia';
import { useRouteQuery } from '../utils/useRoute';
import { openNewTableCompare } from '../router';

const selectKey = "EtfConstructSelect"
const sortPropKey = "WeekDown300DSortProp"
const sortOrderKey = "WeekDown300DSortOrder"

const state = reactive({
    stock: "",
    data: [],

})

const stockSearchStore = weekStockSearch()
let { input } = storeToRefs(stockSearchStore)

// 网址传参
let stock = useRouteQuery("stock")
if(stock) {
    input.value = stock
    state.stock = stock
}

const loadData = () => {
    getStockEtfConstruct(input.value).then( res => {
        state.data = res.data
    })
}

loadData()

// 只监听pinia中某一个值的变化
watch(() => input.value, (newValue, oldValue) => {
    state.stock = newValue
    loadData()
})

const sortChange = (column, prop, order) => {
    sessionStorage.setItem(sortPropKey, column.prop)
    sessionStorage.setItem(sortOrderKey, column.order)
}

const tableCellClassName = ({row, column, rowIndex, columnIndex}) => {
    let property = column.property
    let val =  row[property]
    if (["cur60wPct"].includes(property)) {
        if (val < 0) {
            return 'lt0-cell'
        }
    }

    if (property == "lp") {
        return getLpClassName(val)
    }

    return ''
}

const corr = () => {
    let stocks = []
    stocks.push(state.stock)
    state.data.forEach(item => {
        stocks.push(item.etf)
    })

    openNewTableCompare(stocks)
}
</script>